﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.IO;
using openlaunch;
using System.Reflection;
using IWshRuntimeLibrary;
namespace OpenLauncher
{
    public partial class PluginBrowser : Form
    {
        public PluginBrowser()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {


        }

        private void PluginBrowser_Load(object sender, EventArgs e)
        {
            //Show the form on a new thread
            Thread f = new Thread(new ThreadStart(showform)); //Make a thread for the splashscreen
            f.Start(); //Start the splashscreen
            //Now gather the webpage data
            HttpWebRequest http = (HttpWebRequest)HttpWebRequest.Create("http://stykocompany.com/software/openlaunch/plugins/main.dat");
            HttpWebResponse httpresponse = (HttpWebResponse)http.GetResponse();
            StreamReader reader = new StreamReader(httpresponse.GetResponseStream());
            string httpcontent = reader.ReadToEnd();
            string[] mgm = httpcontent.Split('\n');
            foreach (string s in mgm)
            {
                string[] g = s.Split('|');
                /* g[0] = Name of plugin
                 * g[1] = url of plugin
                 * g[2] = filename of plugin
                 * g[3] = url of plugin info
                 */
                ListViewItem i = new ListViewItem();
                i.Text = g[0];
                i.SubItems.Add(g[1]);
                i.SubItems.Add(g[2]);
                i.SubItems.Add(g[3]);
                i.SubItems.Add(g[4].Replace("\r", ""));
                listView1.Items.Add(i);
            }
            f.Abort();
        }
        public static string URL = "http://stykocompany.com/software/openlaunch/plugins/";
        private void DownloadFile(object sender, EventArgs e)
        {
            //URL
            button1.Enabled = false;
            button1.Text = "Installing";
            WebClient myWebClient = new WebClient();
            // Download the Web resource and save it into the clearview documents folder.
            try
            {
                myWebClient.DownloadFile(URL + listView1.SelectedItems[0].SubItems[3].Text + ".olpk", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//Styko Company//OpenLaunch//" + listView1.SelectedItems[0].SubItems[3].Text + ".olpk");
                // Initialize UAC Prompt to allow for copying to currentdir.
                /*if (!System.IO.File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//Styko Company//OpenLaunch//PI.exe"))
                {
                    myWebClient.DownloadFile(URL + "PluginInstaller.exe", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//Styko Company//OpenLaunch//PI.exe");
                }
                else
                {
                    // The file does exist.
                    System.IO.File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//Styko Company//OpenLaunch//PI.exe");
                    myWebClient.DownloadFile(URL + "PluginInstaller.exe", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//Styko Company//OpenLaunch//PI.exe");
                }*/
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was an error while fetching plugin.\n" + ex.Message);
                return;
            }
            System.Diagnostics.Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//Styko Company//OpenLaunch//PI.exe");
            button1.Text = "Installed";
            if (MessageBox.Show(this, listView1.SelectedItems[0].Text + " was successfully installed! Would you like to add a desktop shortcut to this plugin?", "Installed successfully!", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                //The user wants a desktop shortcut, so load the plugin, extract the icon, and then add the shortcut.
                try
                {
                    byte[] assembly = PluginProtector.DecryptData(System.IO.File.ReadAllBytes(Application.StartupPath + @"/plugins/" + listView1.SelectedItems[0].SubItems[3].Text + ".olp"));
                    var assm = Assembly.Load(assembly);
                    foreach (Type tsype in assm.GetTypes())
                    {
                        foreach (var tys in tsype.GetInterfaces())
                        {
                            if (tys.Name == "OpenPlugin")
                            {
                                try
                                {
                                    OpenPlugin oplugin = (OpenPlugin)Activator.CreateInstance(tsype);
                                    Icon f = oplugin.ProgramIcon;
                                    Random rand = new Random();
                                    int rnd = rand.Next();
                                    Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//Styko Company//OpenLaunch//icons");
                                    string s= Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//Styko Company//OpenLaunch//icons//" + rnd.ToString() + ".ico";
                                    using (FileStream fs = new FileStream(s, FileMode.Create))
                                    {
                                        f.Save(fs);
                                    }
                                    CreateShortcut(Application.ExecutablePath, rnd.ToString() + ".ico", oplugin.Name, "-shortcut -nogui -psexec " + oplugin.Name.Replace(" ", "%20"));
                                    //oplugin.OnStart();
                                    //Form1 f = new Form1();
                                    //f.FillPluginList(oplugin);
                                    //Form1.plugins.Add(oplugin);
                                    break;
                                }
                                catch
                                {
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    //Could not load plugin
                }
            }
            else
            {
                //The user does not want a shortcut, so do not add one, just load the file.
            }
        }
        void showform()
        {
            Application.Run(new SplashScreen());
        }
        public static void CreateShortcut(string path, string iconname, string title, string args)
        {
            string rundllPath = path;
            // Create a new instance of WshShellClass
            WshShellClass WshShell = new WshShellClass();
            // Create the shortcut
            IWshRuntimeLibrary.IWshShortcut MyShortcut;
            string shortcutPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), string.Format("{0}.lnk", title));
            // Choose the path for the shortcut
            MyShortcut = (IWshRuntimeLibrary.IWshShortcut)WshShell.CreateShortcut(shortcutPath);
            // Where the shortcut should point to
            MyShortcut.TargetPath = rundllPath;
            MyShortcut.WorkingDirectory = Path.GetDirectoryName(rundllPath);
            MyShortcut.Arguments = args;
            // Description for the shortcut
            MyShortcut.Description = string.Format("Open {0}", title);

            // Location for the shortcut's icon
            MyShortcut.IconLocation = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//Styko Company//OpenLaunch//icons//" + iconname;

            // Create the shortcut at the given path
            MyShortcut.Save();
        }
        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                Random f = new Random();
                int rnd = f.Next();
                try
                {
                    WebClient myWebClient = new WebClient();
                    Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//Styko Company//OpenLaunch//Images//");
                    myWebClient.DownloadFile(URL + "images/" + listView1.SelectedItems[0].SubItems[5].Text, Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//Styko Company//OpenLaunch//Images//" + "image" + rnd.ToString());
                    pictureBox1.BackgroundImage = Image.FromFile(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//Styko Company//OpenLaunch//Images//" + "image" + rnd.ToString());
                }
                catch
                {
                    //no image
                    if(!System.IO.File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//Styko Company//OpenLaunch//Images//noimage.png"))
                    {
                        WebClient myWebClient = new WebClient();
                    myWebClient.DownloadFile("http://clearview.stykocompany.com/plugins/images/noimage.png", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//Styko Company//OpenLaunch//Images//" + "noimage.png");
                    }
                    pictureBox1.BackgroundImage = Image.FromFile(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "//Styko Company//OpenLaunch//Images//noimage.png");
                }
                //textBox1.Text = listView1.SelectedItems[0].SubItems[1].Text;
                textBox1.Text = listView1.SelectedItems[0].SubItems[2].Text;
                label2.Text = "Author: " + listView1.SelectedItems[0].SubItems[1].Text;
                if (System.IO.File.Exists(Environment.CurrentDirectory + "//Plugins//" + listView1.SelectedItems[0].SubItems[3].Text+".olp"))
                {
                    // File exists so don't allow the download.
                    button1.Text = "Installed";
                    button1.Enabled = false;
                }
                else
                {
                    button1.Enabled = true;
                    button1.Text = "Download";
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DownloadFile(this, e);
        }
    }
}
